package com.jiuyou.storeController.order;

import com.alibaba.fastjson.JSONObject;
import com.jiuyou.storeController.common.StoreBaseController;
import com.ruoyi.adapayDiv.service.IAdapayDivService;
import com.ruoyi.clerkBalance.service.IClerkBalanceService;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.Member;
import com.ruoyi.common.core.domain.entity.StoreUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.CopyUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.member.service.IMemberService;
import com.ruoyi.order.domain.StoreProductOrder;
import com.ruoyi.order.domain.StoreProductOrderHandle;
import com.ruoyi.order.domain.StoreProductOrderVo;
import com.ruoyi.order.service.IStoreProductOrderHandleService;
import com.ruoyi.order.service.IStoreProductOrderService;
import com.ruoyi.product.domain.StoreProduct;
import com.ruoyi.product.domain.StoreProductJoint;
import com.ruoyi.product.domain.StoreProductVerify;
import com.ruoyi.product.service.IStoreProductJointService;
import com.ruoyi.product.service.IStoreProductService;
import com.ruoyi.common.core.domain.entity.StoreUserRole;
import com.ruoyi.product.service.IStoreProductVerifyService;
import com.ruoyi.shopping.domain.MallIntegral;
import com.ruoyi.shopping.service.IMallIntegralService;
import com.ruoyi.sms.service.ISmsTemplateService;
import com.ruoyi.storeUser.service.IStoreUserService;
import com.ruoyi.storeclassify.service.IStoreclassifyService;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.wechat.SmsTemplate;
import com.ruoyi.wechat.Template;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * @author chengliang
 * @date 2021/11/25
 **/
@RestController
@RequestMapping("/store/order")
@Api(tags = {"订单控制器"})
public class OrderStoreController extends StoreBaseController {
    @Autowired
    private IStoreProductOrderService orderService;
    @Autowired
    private IStoreProductOrderHandleService handleService;
    @Autowired
    private IStoreclassifyService classifyService;
    @Autowired
    private IStoreProductService productService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IAdapayDivService adapayDivService;
    @Autowired
    private IStoreProductVerifyService storeProductVerifyService;
    @Autowired
    private IStoreProductJointService productServiceJointService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private IClerkBalanceService clerkBalanceService;
    @Autowired
    private IStoreUserService storeUserService;
    @Autowired
    private IMallIntegralService integralService;
    @Autowired
    private ISmsTemplateService smsTemplateService ;

    @PostMapping("/getListNew")
    public TableDataInfo getListNew(String orderState,Long productId, String verifyCodeTime){
        StoreUserRole role = getStoreUserRole();
        if(role == null){
            return null;
        }
        //StoreProductOrder order = new StoreProductOrder();
        //order.setStoreId(role.getStoreId());

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("storeId",role.getStoreId());
        params.put("productId",productId);
        params.put("verifyCodeTime",verifyCodeTime);

        List<StoreProductVerify> spvList = storeProductVerifyService.selectStoreProductVerifyByParam(params);

        return getDataTable(spvList);
    }

    /**
     * 验卷记录(员工端)
     * */
    @PostMapping("/getVerifyList")
    public TableDataInfo getVerifyList(String orderState,Long productId, String verifyCodeTime){
        Long userId = getLoginStoreUserId();//当前员工id
        StoreUser storeUser = storeUserService.selectStoreUserById(userId);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("storeId",storeUser.getStoreId());
        params.put("productId",productId);
        params.put("verifyCodeTime",verifyCodeTime);

        List<StoreProductVerify> spvList = storeProductVerifyService.selectStoreProductVerifyByParam(params);

        return getDataTable(spvList);

    }

    @PostMapping("/getList")
    @ApiOperation("获取订单列表")
    public TableDataInfo getList(String orderState,Long productId, String createTime){
        StoreUserRole role = getStoreUserRole();
        if(role == null){
            return null;
        }
        StoreProductOrder order = new StoreProductOrder();
        order.setStoreId(role.getStoreId());
        order.setOrderState(orderState);
        order.setProductId(productId);
        /*if(StringUtils.isNotEmpty(verifyCodeTime)){
            order.getParams().put("verifyCodeTimYMDStr",verifyCodeTime);

//            order.setBeginVerifyCodeTime(verifyCodeTime+" 00:00:00");
//            order.setEndVerifyCodeTime(verifyCodeTime+" 23:59:59");
        }*/
        if(StringUtils.isNotEmpty(createTime)){
            order.getParams().put("createTimYMDStr",createTime);
        }
        startPage();
        order.setOrderType("order");
        List<StoreProductOrder> orders = orderService.selectStoreProductOrderList(order);
        System.out.println(orders);
        List<StoreProductOrderVo> resultList= CopyUtils.copyList(orders, StoreProductOrderVo.class);

        System.out.println(resultList);

        resultList.forEach(e->{
            if(DicConstants.ORDER_STATE_Wait_Use.getCode().equals(e.getOrderState())){
                e.setVerifyCode("待核销");
            }
            Member member = memberService.selectMemberById(e.getMemberId());
            if(member != null) {
                e.setMemberName(member.getNickName());
                e.setMemberHeadImg(member.getHeadImg());
                e.setMemberPhone(member.getPhone());
            }
        });
        return getDataTable(resultList);
    }

    /**
     * 获取短信模板列表
     * */
    @PostMapping("/smsTemplateList")
    public TableDataInfo smsTemplateList(com.ruoyi.sms.domain.SmsTemplate smsTemplate) {
        List<com.ruoyi.sms.domain.SmsTemplate> list = smsTemplateService.selectSmsTemplateList(smsTemplate);
        return getDataTable(list);
    }

    /**
     *  发送短信
     * */
    @PostMapping("/sendSms")
    public AjaxResult sendSms(String mobiles,Long orderId,Long templateId){

        String url = "http://120.78.188.185:8088/sms.aspx";
        String param = "action=send&userid=975&account=yfyzm325&password=yfyzm325&mobile="+mobiles+"&content=您好，您的验证码是87997";
        String content = HttpUtils.sendGet(url,param);

        System.out.println(content);

        return toAjax(1);
    }


    @PostMapping("/getClassifyList")
    @ApiOperation("获取订单内全部分类")
    public TableDataInfo getClassify(){
        StoreUserRole role = getStoreUserRole();
        if(role == null){
            return null;
        }
        List<Long> productIds = orderService.selectClassifyList(role.getStoreId());
        List<StoreProduct> produsts = productService.selectStoreProductByIds(productIds);
        ArrayList<StoreProduct> result = new ArrayList<>();
        produsts.forEach(e->{
            StoreProduct s = new StoreProduct();
            s.setId(e.getId());
            s.setProductName(e.getProductName());
            result.add(s);
        });
        return getDataTable(result);
    }

    @PostMapping("/passRefund/{orderId}")
    @ApiOperation("同意退款")
    public JSONObject passRefund(@PathVariable Long orderId){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success",false);
        jsonObject.put("msg","失败");
        StoreUserRole role = getStoreUserRole();
        if(role == null){
            return jsonObject;
        }
        StoreProductOrder order = orderService.selectStoreProductOrderById(orderId);
        order.setRefundStatus(DicConstants.REFUND_STATUS_Pass.getCode());
        order.setRefundPrice(order.getPayPrice());
        order.setUpdateBy(getLoginStoreUserId());
        order.setUpdateType(DicConstants.BUSINESS_Business.getCode());
        //插入操作记录
        StoreUser storeUser = getStoreUser();
        StoreProductOrderHandle handle = new StoreProductOrderHandle();
        handle.setHandleName("同意退款");
        handle.setHandleDetail("商户同意退款");
        handle.setHandleUserId(storeUser.getId());
        handle.setHandleUserType(role.getRoleType());
        handle.setHandleUserName(storeUser.getNickName());
        handle.setCreateBy(storeUser.getId());
        handle.setCreateType(DicConstants.BUSINESS_Business.getCode());
        handleService.insertStoreProductOrderHandle(handle);
        return jsonObject;
    }

    @PostMapping("/refuseRefund/{orderId}")
    @ApiOperation("拒绝退款")
    public JSONObject refuseRefund(@PathVariable Long orderId,String reason){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success",false);
        jsonObject.put("msg","失败");
        StoreUserRole role = getStoreUserRole();
        if(role == null){
            return jsonObject;
        }
        StoreProductOrder order = orderService.selectStoreProductOrderById(orderId);
//        order.setOrderState(DicConstants.ORDER_STATE_Refund_Apply.getCode());
        order.setRefundStatus(DicConstants.REFUND_STATUS_Refused.getCode());
        order.setUpdateBy(getLoginStoreUserId());
        order.setRefundReason(reason);

        order.setUpdateType(DicConstants.BUSINESS_Business.getCode());
        //插入操作记录
        StoreUser storeUser = getStoreUser();
        StoreProductOrderHandle handle = new StoreProductOrderHandle();
        handle.setHandleName("拒绝退款");
        handle.setHandleDetail("商户拒绝退款");
        handle.setHandleUserId(storeUser.getId());
        handle.setHandleUserType(role.getRoleType());
        handle.setHandleUserName(storeUser.getNickName());
        handle.setCreateBy(storeUser.getId());
        handle.setCreateType(DicConstants.BUSINESS_Business.getCode());
        handleService.insertStoreProductOrderHandle(handle);
        return jsonObject;
    }

    /**
     * 售后验卷
     * */
    @PostMapping("/aftersale")
    public AjaxResult aftersale(String aftersaleCode){
        StoreUserRole role = getStoreUserRole();

        Long userId = getLoginStoreUserId();//当前员工id
        StoreUser storeUser = storeUserService.selectStoreUserById(userId);

        Long storeId;
        if(role == null){
            storeId = storeUser.getStoreId();
        }else{
            storeId = role.getStoreId();
        }
        StoreProductOrder order = orderService.selectAftersale(aftersaleCode,storeId);
        Member member = memberService.selectMemberById(order.getMemberId());

        if(order == null){
            return AjaxResult.error("验券失败，该订单不存在");
        }

        //退款中，退款成功 不能核验
        if(DicConstants.REFUND_STATUS_Refunding.getCode().equals(order.getRefundStatus())||DicConstants.REFUND_STATUS_Successed.getCode().equals(order.getRefundStatus())){
            return AjaxResult.error("退款或已退款的订单");
        }
        if(order.getAftersaleOffNum() == 0){
            return AjaxResult.error("售后次数为0，此卷已经用完");
        }

        //使用了 核销就减一
        Long wof = order.getAftersaleOffNum() - 1L;
        order.setAftersaleOffNum(wof);

        //添加 扫码验卷记录表
        StoreProductVerify storeProductVerify = new StoreProductVerify();
        storeProductVerify.setOrderId(order.getId());
        storeProductVerify.setStoreId(order.getStoreId());
        storeProductVerify.setProductId(order.getProductId());
        storeProductVerify.setVerifyCode(order.getAftersaleCode());
        storeProductVerify.setVerifyCodeTime(DateUtils.getNowDate());
        storeProductVerify.setContent("还剩"+wof+"次");
        storeProductVerify.setVerifyType("aftersale");
        storeProductVerifyService.insertStoreProductVerify(storeProductVerify);

        orderService.updateStoreProductOrder(order);

        //项目佣金 加入手工费
        clerkBalanceService.handleBalance(storeId,userId,order.getAftersaleMoney(),DicConstants.HANDLE_BALANCE_ADD.getCode(),"售后手工费","订单id:"+order.getOrderId(),DicConstants.BUSTYPE_BALANCE_PRO.getCode(),"pro");

        return AjaxResult.success();
    }


    @PostMapping("/verify")
    public AjaxResult verify(String verifyCode){
        StoreUserRole role = getStoreUserRole();

        Long userId = getLoginStoreUserId();//当前员工id
        StoreUser storeUser = storeUserService.selectStoreUserById(userId);

        Long storeId;
        if(role == null){
            storeId = storeUser.getStoreId();
        }else{
            storeId = role.getStoreId();
        }
        StoreProductOrder order = orderService.selectVerify(verifyCode,storeId);
        Member member = memberService.selectMemberById(order.getMemberId());

        if(order == null){
            return AjaxResult.error("验券失败，该订单不存在");
        }

        //退款中，退款成功 不能核验
        if(DicConstants.REFUND_STATUS_Refunding.getCode().equals(order.getRefundStatus())||DicConstants.REFUND_STATUS_Successed.getCode().equals(order.getRefundStatus())){
            return AjaxResult.error("退款或已退款的订单");
        }
        if(order.getWriteOffNum() == 0){
            return AjaxResult.error("核销次数为0，此卷已经用完");
        }
//        if(!DicConstants.ORDER_STATE_Wait_Use.getCode().equals( order.getOrderState()) ){
//            return AjaxResult.error("验券失败,验券时间:"+DateUtils.dateTimeHMS(order.getVerifyCodeTime()));
//        }

        //使用了 核销就减一
        Long wof = order.getWriteOffNum() - 1L;
        order.setWriteOffNum(wof);
        //添加 扫码验卷记录表
        StoreProductVerify storeProductVerify = new StoreProductVerify();
        storeProductVerify.setOrderId(order.getId());
        storeProductVerify.setStoreId(order.getStoreId());
        storeProductVerify.setProductId(order.getProductId());
        storeProductVerify.setVerifyCode(order.getVerifyCode());
        storeProductVerify.setVerifyCodeTime(DateUtils.getNowDate());
        storeProductVerify.setContent("还剩"+wof+"次");

        storeProductVerifyService.insertStoreProductVerify(storeProductVerify);

        //查询时间
        order.setVerifyCodeTime(new Date());
        //核销使用完了
        if(wof == 0){
            order.setOrderState(DicConstants.ORDER_STATE_Used.getCode());
            //如果有售后，订单状态改成 售后
            if(order.getIsAfterSales().equals("Y")){
                order.setOrderState(DicConstants.ORDER_STATE_Aftersale.getCode());
            }
        }
        order.setStoreUserId(role.getStoreUserId());
        orderService.updateStoreProductOrder(order);
        adapayDivService.orderDiv(order.getId());

        //storeId=门店id，userId=当前用户，order=订单表，member=用户表,storeUser=门店用户表
        //普通用户有上级计算积分
        //计算项目佣金（有师傅，没师傅）
        //有上级计算分销
        handlePercent(storeId,userId,order,member,storeUser);

        return AjaxResult.success();
    }

    public void handlePercent(Long storeId,Long userId,StoreProductOrder order,Member member,StoreUser storeUser){
        BigDecimal totalPirce = order.getTotalPrice();//订单价格
        //普通用户上级
        if(member.getParentMemberId() != null){
            String mopratio = configService.selectConfigByKey("member_order_percent");//普通用户积分比例
            BigDecimal mopBratio = new BigDecimal(mopratio).setScale(2,RoundingMode.HALF_UP);
            BigDecimal mopPercent=new BigDecimal("1").subtract(mopBratio.divide(new BigDecimal("100"),2,RoundingMode.HALF_UP));
            BigDecimal mopMoney=mopPercent.multiply(totalPirce).setScale(2,RoundingMode.HALF_UP);
            BigDecimal mopPrice = totalPirce.subtract(mopMoney).setScale(2,RoundingMode.HALF_UP);

            //计算上级的积分
            MallIntegral mallIntegral = new MallIntegral();
            mallIntegral.setUserId(userId);
            List<MallIntegral> mallIntegrals = integralService.selectMallIntegralList(mallIntegral);
            if(mallIntegrals.size()>0){
                MallIntegral in = mallIntegrals.get(0);
                in.setIntegralBalance(in.getIntegralBalance().add(mopPrice));
                mallIntegral.setIntegralBalance(in.getIntegralBalance());
                integralService.updateMallIntegral(in);
            }else{
                mallIntegral.setIntegralBalance(mopPrice);
                integralService.insertMallIntegral(mallIntegral);
            }
        }

        //佣金计算
        //获取员工佣金和手工费
        StoreProductJoint storeProductJoint = productServiceJointService.selectStoreProductByStoreIdAndStoreId(order.getStoreId(),order.getProductId());
        BigDecimal staffMoney = storeProductJoint.getStaffMoney();//员工佣金
        BigDecimal asMoney = storeProductJoint.getAsMoney();//手工费
        BigDecimal feiyong = staffMoney.add(asMoney);//员工佣金 + 手工费

        //查询有没有师父
        if(storeUser.getStaffMasterId() != null){
            //有师父
            BigDecimal staffCommissionRate = storeUser.getStaffCommissionRate();//分佣比例
            BigDecimal bili =new BigDecimal("1").subtract(staffCommissionRate.divide(new BigDecimal("100"),2,RoundingMode.HALF_UP));

            BigDecimal storeMoney=bili.multiply(feiyong).setScale(2,RoundingMode.HALF_UP);//当前用户佣金
            BigDecimal masterYongjin = feiyong.subtract(storeMoney).setScale(2,RoundingMode.HALF_UP);//师父佣金
            //给师父增加佣金(老带新)
            clerkBalanceService.handleBalance(storeId,storeUser.getStaffMasterId(),masterYongjin,DicConstants.HANDLE_BALANCE_ADD.getCode(),"徒弟（"+storeUser.getUserName()+"）分成","订单id:"+order.getOrderId(),DicConstants.BUSTYPE_BALANCE_BELT.getCode(),"belt");
            //项目佣金
            clerkBalanceService.handleBalance(storeId,userId,storeMoney,DicConstants.HANDLE_BALANCE_ADD.getCode(),order.getProductName(),"订单id:"+order.getOrderId(),DicConstants.BUSTYPE_BALANCE_PRO.getCode(),"pro");
        }else{
            //项目佣金
            clerkBalanceService.handleBalance(storeId,userId,feiyong,DicConstants.HANDLE_BALANCE_ADD.getCode(),order.getProductName(),"订单id:"+order.getOrderId(),DicConstants.BUSTYPE_BALANCE_PRO.getCode(),"pro");
        }

        //上级店员或者商家 id (分销)
        if(member.getStoreUserId() != null){
            //增加分销佣金
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("storeId", order.getOrderId());
            params.put("storeProductId", order.getProductId());
            //params.put("state", DicConstants.SYS_Y.getCode());
            List<StoreProduct> StoreProductList = productServiceJointService.selectStoreProductJointByParam(params);

            String ratio = configService.selectConfigByKey("clerk_commission_percent");//员工抽佣比例
            BigDecimal Bratio = new BigDecimal(ratio).setScale(2,RoundingMode.HALF_UP);

            BigDecimal platformMoney= order.getPlatformMoney();//平台佣金
            BigDecimal storepercent=new BigDecimal("1").subtract(Bratio.divide(new BigDecimal("100"),2,RoundingMode.HALF_UP));

            BigDecimal storeMoney=storepercent.multiply(platformMoney).setScale(2,RoundingMode.HALF_UP);
            BigDecimal staffPrice = platformMoney.subtract(storeMoney).setScale(2,RoundingMode.HALF_UP);

            Long storeId2 = order.getStoreId();
            Long storeUserId = order.getStoreUserId();
            //adapayBalanceService.handleBalance(storeId,storeMoney,DicConstants.HANDLE_BALANCE_ADD.getCode(),storeProductOrder.getProductName(),"订单id:"+storeProductOrder.getOrderId(),DicConstants.BUSTYPE_BALANCE_DIV.getCode());
            /*System.out.println(storeId);
            System.out.println(staffPrice);
            System.out.println(DicConstants.HANDLE_BALANCE_ADD.getCode());
            System.out.println(order.getProductName());
            System.out.println("订单id:"+order.getOrderId());
            System.out.println(DicConstants.BUSTYPE_BALANCE_DIV.getCode());*/
            //分佣 div
            clerkBalanceService.handleBalance(storeId2,storeUserId,staffPrice,DicConstants.HANDLE_BALANCE_ADD.getCode(),order.getProductName(),"订单id:"+order.getOrderId(),DicConstants.BUSTYPE_BALANCE_DIV.getCode(),"div");
        }

    }


    @RequestMapping("/orderDiv")
    public void orderDiv(Long orderId){
        adapayDivService.orderDiv(orderId);
    }
}
